/**
 * 采集矿床，移动到指定资源点，一直采集
 */

let baser = require("./baser");

// 返回baser的内部生命函数
module.exports = function () {
    return baser(
        /**
         * 准备函数，到达指定位置
         * @param {Creep} creep
         */
        function (creep) {
            // 获取矿床
            let mineral = creep.pos.findClosestByRange(FIND_MINERALS);
            // 获取旁边的容器
            let container = mineral.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: (structure) => structure.structureType == STRUCTURE_CONTAINER &&
                    structure.pos.isNearTo(mineral)
            });
            // 有容器并且上面没有本类采集者
            if (container) {
                let same = container.pos.lookFor(LOOK_CREEPS)[0];
                if (!same || same.memory.role != creep.memory.role) {
                    creep.memory.pos = container.pos;
                    creep.memory.containerid = container.id;
                    return 3;
                }
                else {
                    // 是自己
                    if (creep == same) {
                        creep.memory.pos = container.pos;
                        creep.memory.containerid = container.id;
                        return 3;
                    }
                }
            }
            return 3;
        },
        /**
         * 工作函数，采集
         * @param {Creep} creep
         */
        function (creep) {
            if (creep.pos.findClosestByRange(FIND_STRUCTURES, {
                filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
            }).store[RESOURCE_ENERGY] > 1990) {
                return 3;
            }
            if (creep.harvest(creep.pos.findClosestByRange(FIND_MINERALS))) {
                return 1;
            }
            return 2;
        },
        /**
         * 结束函数，闲逛或其他
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.memory.pos) {
                return 1;
            }
            // 是否在指定位置
            if (creep.pos.isEqualTo(creep.memory.pos.x, creep.memory.pos.y)) {
                return 2;
            }
            // 位置上是否有本类采集者
            let same = Game.getObjectById(creep.memory.containerid).pos.lookFor(LOOK_CREEPS)[0];
            if (same && same.memory.role == creep.memory.role && same != creep) {
                return 1;
            }
            // 前往地点
            creep.moveTo(creep.memory.pos.x, creep.memory.pos.y);
            return 3;
        });
}